﻿using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
using MimeKit.Text;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;

namespace Tools.SMTP
{
    public static class SMTP
    {
        public static async Task<string> SendEmailAsync(SMTPConfig sMTPConfig,string message)
        {
            var messageToSend = new MimeMessage();
            messageToSend.From.Add(new MailboxAddress(sMTPConfig.fromname, sMTPConfig.fromemail));
            foreach (var item in sMTPConfig.toemail)
            {
                messageToSend.To.Add(new MailboxAddress(item, item));
            }
            
            messageToSend.Subject= sMTPConfig.subject;
            messageToSend.Body = new TextPart(TextFormat.Plain) { Text =  message+ "\n\n\n" + sMTPConfig.modeltext };
            using var client = new SmtpClient
            {
                ServerCertificateValidationCallback = (s, c, h, e) => true
            };
            client.AuthenticationMechanisms.Remove("XOAUTH2");
            await client.ConnectAsync(sMTPConfig.smtpaddress, sMTPConfig.smtpport, SecureSocketOptions.Auto);
            await client.AuthenticateAsync(sMTPConfig.fromemail, sMTPConfig.autorizedkey);
            var res=await client.SendAsync(messageToSend);
            await client.DisconnectAsync(true);
            return res;
        }
    }
}
